package com.xzh.seckill.controller;

import com.xzh.seckill.pojo.User;
import com.xzh.seckill.service.IGoodsService;
import com.xzh.seckill.service.IUserService;
import com.xzh.seckill.vo.DetailVo;
import com.xzh.seckill.vo.GoodsVo;
import com.xzh.seckill.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class Goodscontroller {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    //跳转到商品列表页
    //Windos优化前QPS 884.7
    //Linux优化前QPS 728.3
    //页面优化后WindowsQPS 137.7
    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model,User user,HttpServletRequest request,
                         HttpServletResponse response){
        /*if(StringUtils.isEmpty(ticket))
        {
            return "login";
        }
        //User user = (User) session.getAttribute(ticket);
        User user = userService.getUserByCookie(ticket,request,response);
        if(null == user){
            return "login";
        }*/
        //redis中获取页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        //如果不为空直接返回页面
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());
        //return "goodsList";
        //如果为空，手动渲染，存入redis并返回结果
        WebContext webContext = new WebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList",webContext);
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("goodList",html,60, TimeUnit.SECONDS);
        }
        return html;
    }

    @RequestMapping(value = "/toDetail2/{goodsid}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail2(Model model,User user,@PathVariable("goodsid") Long GoodsId,HttpServletRequest request,
                           HttpServletResponse response)
    {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html  = (String) valueOperations.get("goodsDetail:" + GoodsId);
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(GoodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int seckillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        //秒杀还未开始
        if(nowDate.before(startDate)) {
            remainSeconds = (int)(startDate.getTime()-nowDate.getTime())/1000;

        }else if(nowDate.after(endDate)){//秒杀已结束
            seckillStatus = 2;
            remainSeconds = -1;
        }else{//秒杀进行中
            seckillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("seckillStatus",seckillStatus);
        model.addAttribute("goods",goodsVo);
        //return "goodsDetail";
        WebContext webContext = new WebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail",webContext);
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("goodsDetail:"+GoodsId,html,60,TimeUnit.SECONDS);
        }
        return html;
    }

    @RequestMapping("/detail/{goodsid}")
    @ResponseBody
    public RespBean toDetail(Model model, User user, @PathVariable("goodsid") Long GoodsId)
    {
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(GoodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int seckillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;
        //秒杀还未开始
        if(nowDate.before(startDate)) {
            remainSeconds = (int)(startDate.getTime()-nowDate.getTime())/1000;

        }else if(nowDate.after(endDate)){
            seckillStatus = 2;
            remainSeconds = -1;
        }else{
            seckillStatus = 1;
            remainSeconds = 0;
        }
        DetailVo detailVo = new DetailVo();
        detailVo.setGoodsVo(goodsVo);
        detailVo.setRemainSeconds(remainSeconds);
        detailVo.setSeckillStatus(seckillStatus);
        detailVo.setUser(user);
        return RespBean.success(detailVo);

    }
}
